﻿using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model.UI;
using IMClient.Model.DTO;
using IMClient.Config;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using System.Text.Json;

namespace IMClient.ViewModels;

public partial class GroupDetailsViewModel : ObservableObject
{
    private readonly HttpClient _httpClient;

    [ObservableProperty]
    private string name = string.Empty;

    [ObservableProperty]
    private string avatar = string.Empty;

    [ObservableProperty]
    private string groupId = string.Empty;

    [ObservableProperty]
    private ObservableCollection<FriendViewModel> groupMembers;

    public GroupDetailsViewModel(GroupViewModel group)
    {
        _httpClient = new HttpClient();
        Name = group.Name;
        Avatar = group.Avatar;
        GroupId = group.Id;
        GroupMembers = new ObservableCollection<FriendViewModel>();

        GroupNotificationViewModel.GroupAvatarUpdated += OnGroupAvatarUpdated;
        GroupNotificationViewModel.GroupNameUpdated += OnGroupNameUpdated;

        // 加载群成员信息
        _ = LoadGroupMembersAsync();
    }

    private async Task LoadGroupMembersAsync()
    {
        try
        {
            var request = new HttpRequestMessage(HttpMethod.Post, $"{NetWorkConfig.BaseUrl}/group/groupinfo");
            var content = new StringContent(
                JsonSerializer.Serialize(new { groupId = GroupId }), 
                Encoding.UTF8, 
                "application/json");
            request.Content = content;

            var response = await _httpClient.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                var jsonResponse = await response.Content.ReadAsStringAsync();
                var groupInfo = JsonSerializer.Deserialize<GroupInfoResponseDto>(jsonResponse);

                if (groupInfo?.Code == "0000" && groupInfo.Data?.Members != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        GroupMembers.Clear();
                        foreach (var member in groupInfo.Data.Members)
                        {
                            GroupMembers.Add(new FriendViewModel
                            {
                                Id = member.UserId ?? string.Empty,
                                Name = member.UserName ?? string.Empty,
                                Avatar = member.Avatar
                            });
                        }
                    });
                }
            }
        }
        catch (Exception ex)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                MessageBox.Show($"加载群成员失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            });
        }
    }

    [RelayCommand]
    private void SendMessage()
    {
        // 获取 ChatPage 的单例 ViewModel
        var chatViewModel = ChatWindowViewModel.Instance.GetChatPageViewModel();

        if (chatViewModel == null)
            return;

        // 查找是否已存在该群聊的聊天项
        var existingGroup = chatViewModel.ChatParticipants
            .FirstOrDefault(g => g.Id == GroupId);

        if (existingGroup == null)
        {
            // 如果不存在，创建新的聊天项
            var newGroup = new GroupViewModel
            {
                Id = GroupId,
                Name = Name,
                Avatar = Avatar,
                LastMessage = string.Empty,
                LastMessageTime = string.Empty,
                UnreadCount = 0
            };
            chatViewModel.ChatParticipants.Add(newGroup);
            chatViewModel.FilterParticipants(string.Empty);
            chatViewModel.SelectedParticipant = newGroup;
        }
        else
        {
            chatViewModel.SelectedParticipant = existingGroup;
        }

        ChatWindowViewModel.Instance.NavigateToChat();  // 导航到聊天页面 
    }

    [RelayCommand]
    private void DeleteGroup()
    {
        MessageBox.Show("删除群聊功能待实现");
    }

    private void OnGroupAvatarUpdated(string groupId, string newAvatar)
    {
        if (GroupId == groupId)
        {
            Avatar = newAvatar;
        }

    }
    public void OnGroupNameUpdated(string groupId, string newName)
    {
        if (GroupId == groupId)
        {
            Name = newName;
        }
    }
}